//
//  AWHttpService.m
//  ArtWin
//
//  Created by YYS on 2020/8/4.
//  Copyright © 2020 YYS. All rights reserved.
//

#import "AWHttpService.h"
#import <AFNetworking.h>
#import "SVProgressHUD.h"
#import "EncryptionAndDecryption.h"
#import "NSDictionary+JSON.h"
#import "NSString+EncodingData.h"

@interface AWHttpService ()

@property (nonatomic,strong)  AFHTTPSessionManager *session;
@property (nonatomic,retain)  NSURLSessionTask *task;

@end

@implementation AWHttpService

static NSMutableArray *gy_requestTasks;  /*存放请求线程*/

+ (AWHttpService *)service {
    static AWHttpService *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[AWHttpService alloc]init];
    });
    return instance;
}

#pragma mark public
- (void)postWithUrl:(NSString *)url params:(id)param succ:(SuccessBlock)succ fail:(FailureBlock)fail {
    [self configFailedNet];

    NSString *urlString = [NSString stringWithFormat:@"%@%@",BASE_URL,url];
    NSDictionary *headersDic = @{
                              @"sourceChannel":@"",
                              @"packageName":[NSBundle mainBundle].infoDictionary[@"CFBundleIdentifier"],
                              @"version":[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"],
                              @"adid":@"",
                              @"idfa":@"",
                              @"userId":@"",
                              @"uuId":@""};
    
    NSString *encryptHeaders = [[EncryptionAndDecryption sharedInstance] encryptAES:[NSDictionary jsonStringWithDictionary:headersDic] secretKey:apiKey iv:apiKey];
    NSString *encryptParams = [[EncryptionAndDecryption sharedInstance] encryptAES:[NSDictionary jsonStringWithDictionary:param] secretKey:apiKey iv:apiKey];

    NSDictionary *headers = @{
                            @"JOGGHXW":encryptHeaders,
                            @"packageName":@"wuniversal"};
    NSDictionary *params = @{
                            @"SLGPRUTO":encryptParams};
    
    [self.session POST:urlString
            parameters:params
               headers:headers
              progress:nil
               success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (succ){
            NSString *rawString = [[NSString alloc] encodingData:responseObject];
            NSString *responseJson = [[EncryptionAndDecryption sharedInstance] decryptAES:rawString secretKey:apiKey iv:apiKey];
            NSDictionary *responseDic = [NSDictionary dictionaryWithJsonString:responseJson];
            succ(responseDic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hideTip];
        NSInteger errorType = ReqCodeTypeOther;
        if (error.code == NSURLErrorTimedOut) errorType = ReqCodeTypeTimeout;
        if (error.code == NSURLErrorCancelled) errorType = ReqCodeTypeCalceled;
        if (error.code == NSURLErrorNotConnectedToInternet || error.code == NSURLErrorCannotConnectToHost) errorType = ReqCodeTypeNoNetWork;
        
        if (errorType == ReqCodeTypeTimeout || errorType == ReqCodeTypeNoNetWork) {
            [SVProgressHUD showWithStatus:@"网络出错了~"];
        }else{
            [SVProgressHUD showWithStatus:@"请求失败"];
        }
        if (fail) {
            fail(errorType,error);
        }
    }];
}

- (NSString *)urlString:(NSString *)string {
    return [NSString stringWithFormat:@"%@",BASE_URL];
}

- (NSString*)formatData:(NSDictionary *)dic{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
    NSString *jsonString;
    if (!jsonData) {
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

- (void)configFailedNet {
    [[AWHttpService service]reachBilityStatusWithCallBack:^(AFNetworkReachabilityStatus status) {
        if (status == 0) {
            [SVProgressHUD showWithStatus:@"当前没有网络"];
        }
    }];
}

- (void)hideTip {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 隐藏hud
        [SVProgressHUD dismiss];
    });
}

- (void)cancelRequestWithURL:(NSString *)url {
    
    if (url == nil) {
        return;
    }
    
    @synchronized(self) {
        [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task isKindOfClass:[NSURLSessionTask class]]
                && [task.currentRequest.URL.absoluteString hasSuffix:url]) {
                [task cancel];
                [[self allTasks] removeObject:task];
                return;
            }
        }];
    };
}

- (void)cancelAllRequest {
    @synchronized(self) {
        [[self allTasks] enumerateObjectsUsingBlock:^(NSURLSessionTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task isKindOfClass:[NSURLSessionTask class]]) {
                [task cancel];
            }
        }];
        [[self allTasks] removeAllObjects];
    };
}

- (void)reachBilityStatusWithCallBack:(ReachBilityStatusBlock)block;{
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr  startMonitoring];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (block) {
            block(status);
        }
    }];
    [mgr stopMonitoring];
}

- (AFHTTPSessionManager*)session{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!self->_session) {
             self->_session = [AFHTTPSessionManager manager];
            self->_session.responseSerializer = [AFHTTPResponseSerializer serializer];
            self->_session.requestSerializer.timeoutInterval = 10;

        }
    });
    return _session;
}

- (NSMutableArray *)allTasks{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (gy_requestTasks == nil) {
            gy_requestTasks = [[NSMutableArray alloc] init];
        }
    });
    return gy_requestTasks;
}

@end
